<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseAdminController;
use App\Http\Requests\ChapterDetailRequest;
use App\Models\ChapterDetail;
use App\Models\QueryBuilder;
use Illuminate\Http\Resources\Json\JsonResource;
use Spatie\QueryBuilder\AllowedFilter;

use function PHPUnit\Framework\isNull;

class ChapterDetailController extends BaseAdminController
{
    public function index()
    {
        $data = QueryBuilder::for(ChapterDetail::query())
            ->fields()
            ->filters(['title', 'chapter.chapter_name', AllowedFilter::exact('chapter_id')])
            ->includes(['chapterToDetail', 'chapter', 'chapter.programmingLanguage'])
            ->sorts()
            ->page();
        return $this->success(JsonResource::collection($data));
    }
    //添加
    public function store(ChapterDetailRequest $request)
    {
        $data = $request->toArray();
        // $data['content'] =htmlspecialchars($data['content']);
        ChapterDetail::query()->create($data);
        return $this->success();
    }

    //编辑
    public function update(ChapterDetail $chapterdetail, ChapterDetailRequest $request)
    {
        $data = $request->toArray();
        if (!is_null($data['content'])) {
            $data['content'] = htmlspecialchars($data['content']);
        }
        $chapterdetail->update($data);
        return $this->success();
    }

    //删除
    public function destroy(ChapterDetail $chapterdetail)
    {
        $chapterdetail->delete();
        return $this->noContent();
    }
}
